const imageContainer = document.getElementById('image-container');
const loader = document.getElementById('loader');


// Unsplash API
const count = 10;
const apiKey = 'API_KEY';
const apiUrl =`https://api.unsplash.com/photos/random/?client_id=${apiKey}&count=${count}`;

let ready = false;
let imagesLoaded = 0;
let totalImages = 0;


// Helper Function to Set Attributes on DOM Elements
function setAttributes(element,attributes) {
    for(const key in attributes) {
        element.setAttribute(key, attributes[key]);
    }
}

// Check if all images were load
function imageLoaded(){
    console.log('image loaded');
    imagesLoaded++;
    console.log(imagesLoaded);
    if(imagesLoaded === totalImages){
        ready = true;
        loader.hidden = true;
        console.log('ready = ' + ready);
    }
}

// Create Elements For Links & Photos, Add to MOD
function  displayPhotos(){
    imagesLoaded = 0;
    totalImages = photosArray.length;
    console.log('total images',totalImages);
    console.log(photosArray);
    // Run function for each object in photosArray
    photosArray.forEach((photo) => {
        // Create <a> to link
        const item = document.createElement('a');
        setAttributes(item,{
            href:photo.link,
            target: '_blank',
        });
        // Create <img> for photo
        const img = document.createElement('img');
        setAttributes(img,{
            src:photo.src,
            alt:photo.description,
            title:photo.description,
        });
        // Event Listener, check when each is finished loading
        img.addEventListener('load',imageLoaded);
        // Put <img> in <a>, then put both inside imageContainer Element
        item.appendChild(img);
        imageContainer.appendChild(img);
    })
}


// Check to see if scrolling near bottom of page, Load More Photos
window.addEventListener('scroll', ()=>{
    if(window.innerHeight + window.scrollY >= document.body.offsetHeight - 1000 && ready){
        ready = false;
        displayPhotos();
    }
});

// Get photos from Unsplash API
async function getPhotos() {
    try{
        const response = await fetch(apiUrl);
        const data = await response.json();
        console.log(data);
    }catch(error){
        // Catch Error Here
    }
}

// On Load
// getPhotos();
displayPhotos();



